using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
using System.Globalization;

namespace Camalon.Drawing
{
	/// <summary>
	/// Summary description for SizeFConverter.
	/// </summary>
	public class FPointConverter:ExpandableInstanceConverter
	{
		private int _precision = 2;

		public FPointConverter():this(2)
		{
		}

		public FPointConverter( int precision ):base()
		{
			_precision = precision;
		}

		public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
		{
			if ( value is string ) 
			{
				string sVal = (string)value;
				if( sVal.Length == 0 ) return FPoint.Empty;
				if( string.Compare( sVal, "Empty",true, culture) == 0) return FPoint.Empty;
				string[] args = sVal.Split(';');

				float x = float.Parse( args[0], null);
				float y = float.Parse( args[1], null);
				if( _precision >=0 )  
				{
					x = (float)System.Math.Round( x,_precision );
					y = (float)System.Math.Round( y,_precision );
				}

				return new FPoint( x,y);
			}

			return base.ConvertFrom (context, culture, value);
		}

		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
		{

			if( value is FPoint )
			{
				FPoint m = (FPoint) value;
				if( _precision >=0)  
				{
					m.X = (float)System.Math.Round( m.X,_precision );
					m.Y = (float)System.Math.Round( m.Y,_precision );
				}

				if (destinationType == typeof(string)) 
				{
					return String.Format( "{0}; {1}", m.X,m.Y);
				}

				if (destinationType == typeof(InstanceDescriptor) ) 
				{
					ConstructorInfo ctor = typeof(FPoint).GetConstructor(new Type[] {typeof(float), typeof(float)});
					if (ctor != null) return new InstanceDescriptor(ctor, new float[] {m.X,m.Y});
				}
			}
			
			return base.ConvertTo (context, culture, value, destinationType);
		}


	}

}
